<?php
namespace app\mp\admin;
use app\common\service\Order as OrderService;
use app\common\service\SkuPackageV2;
use app\system\admin\Admin;
use think\Cache;
use think\Db;

class TailManageV2 extends Admin
{
    /**
     * 尾货管理
     *
     * @author hhx
     * @date 2022年8月3日
     */
    public function index()
    {
        $action = $this->request->param('action/s', '');
        $status       = $this->request->param('status/s', 0);
        $factoryKV = getFactoryKV(false);
        $sizeList = getSizeKV(false);
        $stallsKV= getStallsKV();
        $data = [];
        //尾货待处理-修改尾货差异
        if($action=='changeSkuDiff'){
            return $this->_changeSkuDiff();
        }
        //尾货待处理-确定出库
        if($action=="checkout"){
            return $this->_checkout();
        }
        //打包待发货-确定发货
        if($action=="delivery"){
            return $this->_delivery();
        }
        //详细
        if($action=="detailList"){
            return $this->_detailList();
        }
        //退出大包
        if($action=="detail_out"){
          return $this->_detail_out();
        }
        //退货
        if($action=="cancelOrders"){
            return $this->_cancelOrders();
        }
        //退出大货
        if($action=="cancelBigOrders"){
            return $this->_cancelOrders(1);
        }

        if ($this->request->isAjax()|| $this->request->param('export')) {
            // 获取分页参数
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $export     = $this->request->param('export/d', 0);
            $sku = $this->request->param('sku', '');
            $factoryIdarr=array_keys($factoryKV);
            $where=[];

            if ($export) {
                set_time_limit(0);
                $page = 1;$limit = 99999;
            }
            //打包待发货，入库明细，出库明细，已完成 走这里
            if($status !=0){
                $orderData= $this->_PackageAction($where,$page,$limit);
            }else{//尾货待处理
                if($sku) $where[] = ['o.sku', '=', $sku];
                $where[] = ['o.factory_id','in',$factoryIdarr];
                $orderData= $this->_PendingTailAction($where,$page,$limit);
                //保存-尾货待处理的统计条数在缓存
                 \think\facade\Cache::set('tail_manage_count_0',$orderData['total']);
            }
            //统计-tab中订单条数
            $data['statData']= $this->StatisTabNum($status,$orderData);

            $data['totaldata']=$orderData['total'];
            $data['data'] = $orderData['list'];

            //导出
            if ($export) {
                $this->DataExpXls('尾货管理列表-' .date('YmdHis'), $data['data'],$status);
                exit;
            }
            $data['status'] = $status;
            $data['count'] = $orderData['total'];
            $data['code'] = 0;
            $data['msg'] = '';

            return json($data);
        }
        $statData=[0,0,0,0,0];

        $assign = [
            'status' => $status,
            'sizeList' => [0 => '请选择'] + $sizeList,
            'factoryKV' => [0 => '请选择'] + $factoryKV,
            'statData'=>$statData,
            'stallsKV' => ['' => '请选择'] + $stallsKV,
            'clientStatus' => config('mimo.client_status'),
        ];

        return $this->assign($assign)->fetch();
    }

    /**
     *  统计-tab中订单条数
     * @date 2022/9/3
     * @author huanghuixiang
     * param  status状态 0待打包，1 待发货，2 待入库，3待出库，4 已完成
     */
    public function StatisTabNum($status,$orderData){
        $sku = $this->request->param('sku', '');
        $client_ordernum = $this->request->param('client_ordernum', '');

        $where_one_two[]=['spd.status', 'in',[1,2]];
        $where_three=[];
        $where_four='';
        //判断搜索栏是否有提交过来订单号
        if(!empty($client_ordernum)) {
            $where_one_two[]=['spd.client_ordernum', '=',$client_ordernum];
            $where_three[]=['client_ordernum', '=',$client_ordernum];
            $where_four =" and client_ordernum='".$client_ordernum."'";
        }
        //搜索栏是否有提交sku
        if(!empty($sku)) {
            $where_one_two[]=['spd.sku', '=',$sku];
            $where_three[]=['sku', '=',$sku];
            $where_four =" and sku='".$sku."'";
        }
        //计算出库明细总数的sql
        $Delivery_details_total =(new SkuPackageV2())->getOutStackTotalNum($where_three);
        //计算 尾货待处理和打包待发货的sql
        $listsql=db('sku_package_detail spd')
            ->field('spd.status')->where($where_one_two)->group('spd.package_num')->buildSql(false);
        //执行
        $statData1= Db::query("select  a.status,count(a.status) as num from ($listsql) a GROUP BY a.status
            union all select  @status:=3 AS status,@num:=".$Delivery_details_total." 
            union all select  @status:=4 AS status,count(*) as num  from (SELECT  id  from wx_sku_package_detail where is_get_into=1 and package_num !=0 ".$where_four." GROUP BY package_num 
                  union all  SELECT  id   from wx_sku_package_detail where  is_get_into=1  and package_num =0 ".$where_four."  GROUP BY client_ordernum  ) d  ");

        //组装
        $count_status=[1,2,3,4];
        //去重并相加
        $array_count_list= array_column(array_filter($statData1),'num','status');
        $data['statData']=[];
        foreach ($count_status as  $key=>$value) {
            //*** 判断tab中status状态，如果相同则 赋值当前统计的数量。
            if($status==$value){
                $data['statData'][$value]=$orderData['total'];
            }else{
                if(isset($array_count_list[$value]))
                     $data['statData'][$value]=$array_count_list[$value];
                else $data['statData'][$value]=0;
            }
        }
        //尾货待处理统计数量
        $tail_manage_count_0= \think\facade\Cache::get('tail_manage_count_0');
        //在数组前追加一列
        array_unshift($data['statData'],$tail_manage_count_0);

        return $data['statData'];
    }
    /**
     * 入库操作
     * @author hhx
     * 2022-08-18
     */
    public function stockCheckIn(){

        $orderId = $this->request->param('order_id');
        $sizeName=$this->request->param('size_name');
        $dressCode=trim($this->request->param('dress_line_code'),";");
        $stockType=$this->request->param('stocktype');
        $defective_reason=$this->request->param('defective_reason');
        $orderService = new OrderService();
        $orderInfo = $orderService->getInfoById($orderId, 'sku,client_ordernum,factory_id');
        $dressCode=$dressCode.";";
        $dressCodeArr=explode(";",$dressCode);
        unset($dressCodeArr[count($dressCodeArr)-1]);
        foreach ($dressCodeArr as $key=>$dressCodeStr){
            $newDressArr[$dressCodeStr]=$key;
        }
        if(empty($orderInfo)){
            return $this->Json(0,'订单号有误,请确认');die;
        }
        if(count($newDressArr)>1){
            return $this->Json(0,'存在不同的条码,请确认');die;
        }
        $oldstock=0;

        $oldStockInfo=db('sku_stock')->where(['sku' => $orderInfo['sku'], 'factory_id' => $orderInfo['factory_id'],'size_name'=>$sizeName,'client_ordernum' => $orderInfo['client_ordernum']])->find();

        $has_dress_code=db('sku_stock')->where(['dress_line_code' => $dressCodeArr[0]])->find();

        if($oldStockInfo && $oldStockInfo['dress_line_code']!=$dressCodeArr[0] && !empty($oldStockInfo['dress_line_code'])){
            return $this->Json(0,$sizeName.'已入库，条码为'.$oldStockInfo['dress_line_code'].',请确认当前条码');die;
        }

        if($has_dress_code ){
            if($has_dress_code['size_name']!=$sizeName || $has_dress_code['sku']!=$orderInfo['sku'] || $has_dress_code['client_ordernum']!=$orderInfo['client_ordernum']){
                return $this->Json(0,'条码'.$dressCodeArr[0].'已入库,对应订单号：'.$has_dress_code['client_ordernum'].',尺码：'.$has_dress_code['size_name'].'');die;
            }
        }
        $package_info=db('sku_package_detail')->where(['client_ordernum' => $orderInfo['client_ordernum'],'size_name'=>$sizeName])->field('tail_goods_dff')->find();

        if($package_info['tail_goods_dff']<=0){
            return $this->Json(0,'尾货差异要大于0才能入库,请确定');die;
        }

        try {
            db()->startTrans();
            $actiontime=time();
            $savedata = ['sku' => $orderInfo['sku'],'available_detail' =>'{"'.$sizeName.'":"'.count($dressCodeArr).'"}',
                'available_count' =>count($dressCodeArr),'size_name'=>$sizeName, 'dress_line_code'=>$dressCodeArr[0],'factory_id'=>$orderInfo['factory_id'],'update_time' => $actiontime,'client_ordernum'=>$orderInfo['client_ordernum']];
            if($stockType=='defective'){
                unset($savedata['available_detail']);unset($savedata['available_count']);
                $savedata['defective_count']=count($dressCodeArr);$savedata['defective_detail']='{"'.$sizeName.'":"'.count($dressCodeArr).'"}';$savedata['defective_reason']=$defective_reason;
            }
            if(!$oldStockInfo){
                $savedata['create_time']=$actiontime;
                db('sku_stock')->insert($savedata);
            }else{
                $oldstock=$oldStockInfo['available_count'];
                $savedata['dress_line_code']=$dressCodeArr[0];
                $savedata['available_detail']='{"'.$sizeName.'":"'.($oldstock+count($dressCodeArr)).'"}';
                $savedata['available_count']=$oldStockInfo['available_count']+count($dressCodeArr);
                if($stockType=='defective'){
                    unset($savedata['available_detail']);unset($savedata['available_count']);
                    $savedata['defective_count']=$oldStockInfo['defective_count']+count($dressCodeArr);$savedata['defective_detail']='{"'.$sizeName.'":"'.($oldStockInfo['defective_count']+count($dressCodeArr)).'"}';
                    $savedata['defective_reason']=$defective_reason;
                }
                db('sku_stock')->where(['id' => $oldStockInfo['id']])->update($savedata);
            }
            $stock_log = ['sku' => $orderInfo['sku'], 'uid' =>ADMIN_ID,'action_type' => 1,'available_detail' =>'{"'.$sizeName.'":"'.count($dressCodeArr).'"}',
                'factory_id' =>$orderInfo['factory_id'],'create_time' => $actiontime,'client_ordernum'=>$orderInfo['client_ordernum']];
            if($stockType=='defective'){
                unset($stock_log['available_detail']);
                $stock_log['defective_count']=count($dressCodeArr);
                $stock_log['defective_detail']='{"'.$sizeName.'":"'.count($dressCodeArr).'"}';$stock_log['defective_reason']=$defective_reason;$stock_log['remark']=$defective_reason;
            }else{
                $stock_log['available_count']=count($dressCodeArr);
            }
            db('sku_stock_log')->insert($stock_log);

            //更新包状态、尾货差异数量
            $update_data['tail_goods_dff']=$package_info['tail_goods_dff']-count($dressCodeArr);
            $update_data['update_time']=time();
            if($update_data['tail_goods_dff'] <=0){
                $update_data['status']=4;
            }
            $update_data['is_get_into']=1;
            db('sku_package_detail')->where(['client_ordernum' => $orderInfo['client_ordernum'],'size_name'=>$sizeName])->update($update_data);

            db()->commit();
            $savedata['checkin_count']=count($dressCodeArr);
            $savedata['size_name']=$sizeName;
            return $this->Json(1,'success',$savedata);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 扫码出库操作
     * @author hhx
     */
    public function stockCheckOut(){
         $idlist= $this->request->param('order_id');
        $dressCode=trim($this->request->param('out_dress_line_code'),"\n");
        $orderId_list=array_filter(explode(',',$idlist));
        $orderInfo_list = db('order')->field('sku,client_ordernum,factory_id')->where('id','in',$orderId_list)->select();
        $dressCodeArr=explode("\n",$dressCode);
        $newDressArr=[];

        foreach ($dressCodeArr as $key=>$dressCodeStr){
            if(!isset($newDressArr[$dressCodeStr])){
                $newDressArr[$dressCodeStr]=1;
            }else{
                $newDressArr[$dressCodeStr]++;
            }
        }
        $client_ordernum_list=array_column($orderInfo_list,'sku');
        $stockList=db('sku_stock')->where(['sku' => $client_ordernum_list,'dress_line_code'=>array_keys($newDressArr)])->select();
        if(count($stockList)<count($newDressArr)){
            return $this->Json(0,'出库条码有误，有不存在的出库条码');die;
        }
        $orders=array_unique($orderId_list);
        if(count($orders)>1){
            return $this->Json(0,'暂时不支持 同时选择多个订单出库！');die;
        }

        $availableCountArr=array_column($stockList,'available_count','dress_line_code');

        foreach ($availableCountArr as $index=>$stockcount){
            if($newDressArr[$index]>$stockcount){
                return  $this->Json(0,$index.'出库数量'.$newDressArr[$index].'件超过总库存'.$stockcount.'件，库存不足,请确认');die;
            }
        }

        try {
            db()->startTrans();

            $actiontime=time();
            $act_ret_str='';
            $SkuPackage= new SkuPackageV2();

            foreach ($stockList as $key=>$stockinfo){

                $savedata = ['sku' => $stockinfo['sku'],'available_detail' =>'{"'.$stockinfo['size_name'].'":"'.($stockinfo['available_count']-$newDressArr[$stockinfo['dress_line_code']]).'"}',
                    'available_count' =>$stockinfo['available_count']-$newDressArr[$stockinfo['dress_line_code']],'update_time' => $actiontime];

                db('sku_stock')->where(['id' => $stockinfo['id']])->update($savedata);
                $stock_log = ['sku' => $stockinfo['sku'], 'uid' =>ADMIN_ID,'available_count'=>$newDressArr[$stockinfo['dress_line_code']],'out_ordernum'=>$stockinfo['client_ordernum'],
                    'action_type' => 2,'available_detail' =>'{"'.$stockinfo['size_name'].'":"'.$newDressArr[$stockinfo['dress_line_code']].'"}',
                    'factory_id' =>$stockinfo['factory_id'],'create_time' => $actiontime,'client_ordernum'=>$stockinfo['client_ordernum'],'remark'=>$stockinfo['client_ordernum']."出货调用"];
                db('sku_stock_log')->insert($stock_log);
                $act_ret_str=$act_ret_str.$stockinfo['size_name'].":".$newDressArr[$stockinfo['dress_line_code']]."件，";

                //更新包状态
                $tail_goods_dff=$SkuPackage->getInfoByOrderSizeName($orders[0],$stockinfo['sku'],$stockinfo['size_name']);
                if($tail_goods_dff<0){
                    $diff_num= $tail_goods_dff+$newDressArr[$stockinfo['dress_line_code']];
                    if($diff_num>0){
                        return $this->Json(0,'出库数量：'.$newDressArr[$stockinfo['dress_line_code']].' 已超过尾货差异数量：'.$tail_goods_dff.' ,请确认');die;
                    }
                }
                else{
                    return $this->Json(0,'尾货差异不能为正数');die;
                }

                //为大于等于0的时候,直接完成
                if($diff_num==0){
                    $update_data['status']=4;
                }
                //计算尾货差异数量
                $update_data['is_get_into']=1;
                $update_data['tail_goods_dff']=$diff_num;
                $update_data['update_time']=time();

                db('sku_package_detail')->where(['order_id' => $orders[0],'size_name'=>$stockinfo['size_name']])->update($update_data);
            }
            db()->commit();
            $savedata['act_ret_str']=$act_ret_str;
            return $this->Json(1,'success',$savedata);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, "操作失败，". $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    //退货  $type 0为入库明细-退货，1为尾货待处理-退出大货
    public function _cancelOrders($type=0){
        $list=$this->request->param();
        if(empty($list['ids_str'])) return $this->error('请选择要操作的数据');
        $strlist= explode(',',$list['ids_str']);
        $msn='';
        try {
            db()->startTrans();
            foreach($strlist as $key=>$val){
                if(!empty($val)){
                    if($type==1){
                        $packageNumList=db('sku_package_detail')->field('client_ordernum,size_name')->where(['package_num'=>$val])->select();
                        foreach ($packageNumList as $value){
                            db('order_size')->where(['client_ordernum'=>$value['client_ordernum'],'size_name'=>$value['size_name']])->update(['is_tail_manage'=>0]);
                        }
                        db('sku_package')->where(['package_num'=>$val])->delete();
                        db('sku_package_detail')->where(['package_num'=>$val])->delete();
                        $msn='';
                    }else{
                        db('sku_package')->where(['package_num'=>$val])->update(['status'=>1,'return_status'=>1,'update_time'=>time()]);
                        db('sku_package_detail')->where(['package_num'=>$val])->update(['status'=>1]);
                    }
                };
            }
            db()->commit();
            return $this->Json(1,$msn);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }
    //详细
    public function _detailList(){

        $param  = $this->request->param();
        $package_num_ok  = $this->request->param('package_num', 0);
        $val        = $this->request->param('val/d', 0);
        $status        = $this->request->param('status/s', 0);
        $status_two        = $this->request->param('status_two', 0);
        $a        = $this->request->param('a/s', '');
        $is_order=$this->request->param('is_order', 0);;
        $field_type=$this->request->param('field_type', '');

        //判断传递过来的是否订单号
        if(isset($param['client_ordernum']) || $is_order==1){
            $is_order=1;
            $package_num=isset($param['client_ordernum'])?$param['client_ordernum']:$param['package_num'];
        }else{
            $package_num=$package_num_ok;
        }
        $package_num_list=array_filter(explode(',',$package_num));

        if ($this->request->isAjax()) {
            $where      = $data = $diff_data=[];
            $data['data']=[];


            //针对出库明细-详细 ，走这里
            if($is_order==1 && $status !=-100){

                unset($where);
                $model= new OrderService();
                $where[]=['pd.status','=',3];
                $where[]=['pd.client_ordernum','in',$package_num_list];
                //$where[]=['sst.available_count','>',0];
                $data['data']=db('sku_package_detail pd')
                    ->join('sku_stock sst',  'pd.client_ordernum = sst.client_ordernum  and  pd.size_name=sst.size_name','left')
                    ->join('sku sk ', ' pd.sku=sk.sku','left')
                    ->join('factory f', 'pd.factory_id = f.id','left')
                    ->field('pd.*,sk.ori_pic,f.name as factory_name')
                    ->where($where)
                    ->select();

                $data['count'] = count($data['data']);

                foreach ($data['data'] as $key=>$val){
                    //正品库存总数
                    $countOut=db('sku_stock')->field('sum(available_count) as total_num_one')->where(['sku'=>$val['sku'],'size_name'=>$val['size_name']])->group("size_name")->find();

                    //如库存为零的不显示
                    if($val['tail_goods_dff']==0){
                        unset($data['data'][$key]);
                        continue;
                    }
                    if(empty($countOut['total_num_one'])) $countOut['total_num_one']=0;

                    $list[$key]['total_num_need']=$val['need_put_num'];
                    $data['data'][$key]['available_count_total'] =$countOut['total_num_one'];

                    //获取服装码
                    $otherStockList=db('sku_stock')->where(['sku'=>$val['sku'],'size_name'=>$val['size_name']])
                        ->field('dress_line_code')->select();
                    $str='';
                    foreach ($otherStockList as $value){
                        $str .=$value['dress_line_code'].',';
                    }
                    $data['data'][$key]['otherStockList_json']=$str;

                    $orderInfo=$model->getInfoByClientOrdernum($val['client_ordernum'],'id as order_id,tail_over_time');
                    if($orderInfo){
                        $data['data'][$key]['order_id']=$orderInfo['order_id'];
                        $data['data'][$key]['tail_over_time']=$orderInfo['tail_over_time'];
                    }
                     //前端页面显示总数统计
                    $diff_data[$key]['client_ordernum']=$val['client_ordernum'];
                    $diff_data[$key]['package_num']=$val['package_num'];
                    $diff_data[$key]['total_num']=$countOut['total_num_one'];
                }

            }else{

                if(!empty($status)){
                    //将传递过来的status 定义为-100，意思就是 即从 “已完成”，过来。避免和status=4冲突.因为 “已完成” 这一趴，有很多订单状态如、2,3，4，。而is_get_into=1 是进入完成状态
                    if($status==-100) $where[]=['pd.is_get_into','=',1];
                    else $where[]=['pd.status','=',$status];
                }
                if($field_type=="client_ordernum"){
                    $where[]=['pd.client_ordernum','in',$package_num_list];
                    $group_diff='pd.package_num';
                    $field_diff='sum(tail_goods_dff) as total_num,client_ordernum';
                }else{
                    $group_diff='pd.package_num';
                    $field_diff='sum(tail_goods_dff) as total_num,package_num';
                    $where[]=['pd.package_num','in',$package_num_list];
                }

                $data['data']= db('sku_package_detail pd')
                    ->join('sku sk ', ' pd.sku=sk.sku','left')
                    ->join('factory f', 'pd.factory_id = f.id','left')
                    ->field('pd.*,sk.ori_pic,f.name as factory_name')
                    ->where($where)
                    ->select();


                foreach ($data['data'] as $keyNum=>$valNum){

                    if($status==-100  && $valNum['tail_goods_dff']==0){

                        $data['data'][$keyNum]['tail_goods_dff']=$valNum['need_put_num'];
                        $data['data'][$keyNum]['over_status']=1;
                    }else if($status==-100){

                        $data['data'][$keyNum]['over_status']=0;
                        $data['data'][$keyNum]['tail_goods_dff']=$valNum['need_put_num']-$valNum['tail_goods_dff'];
                        $data['data'][$keyNum]['diffNum']=$valNum['tail_goods_dff'];
                    }

                }

                $data['count'] = db('sku_package_detail pd')->where($where)->count('id');
                $diff_data = db('sku_package_detail pd')->field($field_diff)->where($where)->group($group_diff)->select();
            }

            $total_count='';
            //前端页面显示总数统计
            foreach ($diff_data as $key=>$value){
                if($is_order==1 || $field_type=="client_ordernum"){
                    $strnum="订单号：".$value['client_ordernum'];
                }else{
                    $strnum="大包号：".$value['package_num'];
                }
               $total_count .=$strnum.",&nbsp;&nbsp;总数：".$value['total_num']."；";
            }

            $data['data']= array_values($data['data']);
            $data['total_count'] = $total_count;
            $data['code'] = 0;
            $data['msg'] = '';
            $data['status']=$status;

            return json($data);
        }


        $assign = [
            'is_order' => $is_order,
            'val'=>$val,
            'field_type'=>$field_type,
            'package_num'=>$package_num,
            'status'=>$status,
            'status_two'=>$status_two,
            'a'=>$a
        ];
        $template = $this->request->param('template', 'detail_list');
        return $this->assign($assign)->fetch($template);
    }

    //详细-退出大包
    public function _detail_out(){
        $ids_str = $this->request->param('ids_str', '');
        $status = $this->request->param('status', '0');
         if($status ==3) return $this->error('出库-不能退出大包');
        $idlist=array_filter(explode(',',$ids_str));
        try {
            db()->startTrans();
             if(!empty($idlist)) {
                 foreach ($idlist as $value){
                     $info= explode('|',$value);
                        db('sku_package_detail')->where(['client_ordernum'=>$info[0],'size_name'=>$info[1]])->delete();
                        db('order_size')->where(['client_ordernum'=>$info[0],'size_name'=>$info[1]])->update(['is_tail_manage'=>0]);
                        $this->addOrderLog(0, $info[0], '尺码：'.$info[1].'退出大包成功');
                        db()->commit();
                        return $this->Json(1,'退出大包成功');
                 }
             }
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }
    //尾货待处理
    public function  _PendingTailAction($where,$page,$limit){
        $size_name = $this->request->param('size_name', '');
        $stock_method = $this->request->param('stock_method', '');
        $client_ordernum   = $this->request->param('client_ordernum', '');
        $factoryId   = $this->request->param('factory_id/d', 0);
        $resault=[];
        $where1=$where2=[];
        if(!empty($client_ordernum)) $where[] = ['o.client_ordernum', '=', $client_ordernum];
        if(!empty($factoryId)) $where[] = ['o.factory_id', '=', $factoryId];
        if(!empty($remark)) $where[] = ['t2.size_name', '=', $size_name];
        if(!empty($size_name)) $where[] = ['t2.size_name', '=', $size_name];
        if(!empty($where))$where1=$where;$where3=$where;

        $where1[] = ['o.status','in',[0,1]];
        $where1[] = ['t2.is_tail_manage','=',0];
        $where2[]= ['t6.daohuo_count','>',0];//实际出货数大于0
        $where2[]= ['t6.tail_goods_dff','<>',0];//尾货差异不等于0
        $where3[]= ['t2.is_tail_manage','=',-1];

        $field="o.sku,o.id as order_id,o.tail_over_time,t2.is_tail_manage,t2.factory_id,t2.size_name,t2.client_ordernum,t2.order_count,t2.shicai_count,
t2.jiaohuo_count,t2.daohuo_count,t2.jiaohuo_tail_count,(cast(t2.jiaohuo_count as signed) - cast(t2.daohuo_count as signed)) as tail_goods_dff,
t2.tail_stock_in_out,sk.stock_finished,sk.ori_pic,f.name as factory_name";
        $field2=$field.'';
        /** 尾货待处理这里的sql 实现原理
         *  1、对$where1,$where2里面的条件查询筛选 2、然后联合查询 新增入库单的 数据。
         *  因为新增入库单的数据 没有任何where条件，只要定义is_tail_manage= -1就可以让它显示。并且计算出总库存
         */

        $totalsqlson = db('order o')
            ->join('order_size t2', 'o.id = t2.order_id','left')
            ->join('sku sk', 'o.sku = sk.sku','left')
            ->join('factory f', 'o.factory_id = f.id','left')
            ->where($where1)
            ->field($field)
            ->buildSql();
        $orderDataModel=Db::table($totalsqlson.' t6')->where($where2);

        //针对搜索栏-出入库搜索
        $where_stock='';
        if(!empty($stock_method)){
            if($stock_method==2){
                $where_stock =' and tail_goods_dff <0';
            }else{$where_stock =' and tail_goods_dff >0';}
        }
        $sql1=$orderDataModel->buildSql();
        $sql2 = db('order o')
            ->join('order_size t2', 'o.id = t2.order_id','left')
            ->join('sku sk', 'o.sku = sk.sku','left')
            ->join('factory f', 'o.factory_id = f.id','left')
            ->where($where3)
            ->field($field2)
            ->buildSql();

        //库存计算，在$totalStockSql里面了。
        $totalStockSql='SELECT * from (SELECT t12.*,(select sum(st.available_count)  from wx_sku_stock st where t12.sku=st.sku  and  t12.size_name =st.size_name GROUP BY st.size_name limit 1) as stock_count from ';
        $sql3=' t12 ) t13  where  (tail_goods_dff>0 or (tail_goods_dff <0 and  stock_count >0)) '.$where_stock;
        //联合查询
        $allSql='('.$totalStockSql.'('.$sql1.' union all '.$sql2.')'.$sql3.')';

        //统计
        $resault['total']=DB::table($allSql.' t16 ')->count();
        //列表数据
        $list= DB::table($allSql.' t16')->orderRaw("is_tail_manage asc,tail_over_time desc")->page($page)->limit($limit)->select();

        if($resault['total']>0){
            foreach($list as $key=>$val){
                $list[$key]['id']= $key+1;
                $list[$key]['pack_status_stay']= "待打包";
                if(!empty($val['tail_over_time'])) $list[$key]['tail_over_time']= date("Y-m-d H:i:s",$val['tail_over_time']);
                else  $list[$key]['tail_over_time']='';
                $list[$key]['stock_outtype']=$val['tail_goods_dff'] >0 ? "入库":'出库';
            }
        }
        $resault['list']=$list;
        return $resault;
    }

    //包状态
    public function  getPackageStatus($status=0,$is_get_into=0){
        $str='';
        if($is_get_into==1)$status=4;
        switch ($status) {
            case 1:
                $str = "待发货";
                break;
            case 2:
                $str = "待入库";
            case 3:
                $str = "待出库";
                break;
            case 4:
                $str = "已完成";
                break;
            case -1:
                $str = "<font color='#cd5c5c'>已退货</font>";
                break;
            default:
                $str = "待打包";
        }
        return $str;
    }
    //处理原因
    public function  get_reason_content($is_reason,$reason_content){

        switch ($is_reason) {
            case 1:
                $str = "车间补片";
                break;
            case 2:
                $str = "有报废品";
                break;
            case 3:
                $str = $reason_content;
                break;
            default:
                $str = "";
        }
        return $str;
    }

    //尾货包-action
    public function _PackageAction($where,$page,$limit){
        $factoryId = $this->request->param('factory_id', '');
        $status = $this->request->param('status', 0);
        $package_num = $this->request->param('package_num', '');
        $create_time = $this->request->param('create_date_range', '');
        $client_ordernum   = $this->request->param('client_ordernum', '');
        $remark   = $this->request->param('remark', '');
        $sku   = $this->request->param('sku', '');


        if(!empty($sku)) $where[] = ['spd.sku', '=', $sku];
        if(!empty($package_num)) $where[]= ['spd.package_num','=',$package_num];
        if(!empty($factoryId)) $where[]=['spd.factory_id','=',$factoryId];
        if(!empty($client_ordernum)) $where[] = ['spd.client_ordernum', '=', $client_ordernum];
        if(!empty($create_time)){
            list($startTime, $endTime) = $create_time != '' ? array_map('strtotime', explode('~', $create_time)): '';
           $where[] =  ['spd.create_time', 'between', [$startTime,$endTime]];
        }

        $resault=[];
        //如果是-出库明细
        if($status ==3){
            $total=1;//给个默认值，无用的，在底部会赋值新的值
            $where[]=['spd.status','=',3];
            $group='spd.client_ordernum';
            if(!empty($remark)){
                 if($remark==2){
                     $where[]=['o.remark','=',"尾货"];
                 }else{
                     $where[]=['o.remark','neq',"尾货"];
                 }
            }
            if(!empty($package_num)) $where[]= ['spd.package_num','=',$package_num];
            $field='spd.id,spd.client_ordernum,spd.sku,spd.size_name,spd.need_put_num,spd.create_time,f.name as factory_name_two,spd.tail_goods_dff,o.id as order_id,o.tail_over_time,o.remark';
            $list= db('sku_package_detail spd')
                ->join('factory f', 'spd.factory_id = f.id','left')
                ->join('sku_stock st', 'spd.client_ordernum = st.client_ordernum  and  spd.size_name=st.size_name','left')
                ->join('order o', 'spd.client_ordernum = o.client_ordernum','inner')
                ->field($field)
                ->where($where)->group($group)->page($page)->order('spd.id desc')->limit($limit)->select();

        //如果是-已完成
        }else if ($status==4){
            if(!empty($status)) $where[] = ['spd.is_get_into', '=', 1];
            $where1=$where2=$where;
            $where1[]= ['spd.package_num','<>',0];
            $where2[]=['spd.package_num','=',0];
            $group1='spd.package_num';
            $group2='spd.client_ordernum';
            $orderby='spd.update_time';
            $field='spd.id,spd.order_id,spd.is_reason,spd.is_get_into,spd.reason_content,spd.update_time,spd.package_num,spd.client_ordernum,spd.create_time,sp.return_status,spd.status,f.name as factory_name_two,sum(spd.tail_goods_dff) as total_num,sum(spd.need_put_num) as total_need_num,count(DISTINCT(spd.client_ordernum)) as  total_ordernum';
            //联合查询- 分别group by 订单号和包号，然后将数据集合一起
            $ordersql1= db('sku_package_detail spd')->join('sku_package sp', 'spd.package_num = sp.package_num','left')
                ->join('factory f', 'spd.factory_id = f.id','left')->where($where1)->group($group1)->field($field)->order($orderby)->buildSql();
            $ordersql2 =db('sku_package_detail spd')->join('sku_package sp', 'spd.package_num = sp.package_num','left')
                ->join('factory f', 'spd.factory_id = f.id','left')->where($where2)->group($group2)->field($field)->order($orderby)->buildSql();
            $ModelOrder= Db::table($ordersql1.' aa')->union($ordersql2,true);
            $total=count($ModelOrder->select());
            $list=$ModelOrder->page($page)->order('update_time')->limit($limit)->select();
        //如果是-打包待发货或出库明细
        }else{
            if(!empty($status)) $where[] = ['spd.status', '=', $status];
            $total =db('sku_package_detail spd')
                ->join('sku_package sp', 'spd.package_num = sp.package_num','left')
                ->join('factory f', 'spd.factory_id = f.id','left')
                ->where($where)
                ->group(  'spd.package_num')
                ->distinct(true)->field('spd.package_num')
                ->count();
            $list= db('sku_package_detail spd')
                ->join('sku_package sp', 'spd.package_num = sp.package_num','left')
                ->join('factory f', 'spd.factory_id = f.id','left')
                ->field('spd.id,spd.order_id,spd.package_num,spd.client_ordernum,spd.create_time,sp.return_status,spd.status,f.name as factory_name_two,sum(spd.tail_goods_dff) as total_num,sum(spd.need_put_num) as total_need_num,count(DISTINCT(client_ordernum)) as  total_ordernum')
                ->where($where)->group('spd.package_num')->page($page)->limit($limit)->select();

        }

        if($total>0){
            foreach($list as $key=>$val){
                //如果是-出库明细
                if($status==3){
                    $total_num_need=0;//总库存数
                    $total_num=0;//总件数
                    $need_put_num=0;//需要出库
                    $total_ordernum=0;//总单数
                    $str='';
                    $order_list= db('sku_package_detail')->field('sku,size_name,client_ordernum,tail_goods_dff,need_put_num')->where('client_ordernum',$val['client_ordernum'])->select();

                    foreach ($order_list as $key_two=>$value){
                        //获取需要出库的数量（需要获取该订单sku 对应尺码的总库存数）
                        $countOut=db('sku_stock')->field('sum(available_count) as total_num_one')->where(['sku'=>$value['sku'],'size_name'=>$value['size_name']])->group("size_name")->find();
                        $total_num_need +=$countOut['total_num_one'];
                        $total_num +=$value['tail_goods_dff'];
                        $need_put_num +=$value['need_put_num'];
                        $total_ordernum++;
                        //处理服装码
                        $dress_line_code=db('sku_stock')->field('dress_line_code')->where(['sku'=>$value['sku'],'size_name'=>$value['size_name']])->select();
                        foreach ($dress_line_code as $valueList){
                            $str .=$valueList['dress_line_code'].',';
                        }
                    }

                    if($total_num==0){
                        unset($list[$key]);
                        continue;
                    }

                    //如库存为零的不显示
                    $list[$key]['total_num'] = $total_num;//总单数
                    $list[$key]['total_ordernum']=$total_ordernum;//总件数

                    $list[$key]['total_need_out_num']=$need_put_num;
                    //服装码
                    $list[$key]['otherStockList_json']=$str;
                    //尾完时间
                    if(!empty($val['tail_over_time'])){
                        $list[$key]['tail_over_time']= date('Y-m-d H:i:s',$val['tail_over_time']);
                    }else{
                        $list[$key]['tail_over_time']= '';
                    }

                    $list[$key]['status']=3;
                    $list[$key]['d_status']=$this->getPackageStatus($status);
                    $list[$key]['remark']=$val['remark'];
                    $list[$key]['package_num']=0;
                    $list[$key]['order_id']=$val['order_id'];
                    unset($str);
                 //如果是已完成
                }else if($status==4) {

                    $list[$key]['reason_content']= isset($val['is_reason'])?$this->get_reason_content($val['is_reason'],$val['reason_content']):"";
                    $list[$key]['d_status']= $this->getPackageStatus($val['status'],$val['is_get_into']);
                    $list[$key]['tail_goods_dff_end']= $val['total_need_num'];
                    //如为零，直接显示完成的件数
                    if($val['total_num']==0){
                        $list[$key]['total_num'] = $val['total_need_num'];//总单数
                    }else{
                        $list[$key]['total_num'] = $val['total_need_num']-$val['total_num'];//总单数
                    }

                    if(empty($val['package_num'])){
                        $list[$key]['packageOrder_num']= $val['client_ordernum'];
                    }else{
                        $list[$key]['packageOrder_num']= $val['package_num'];
                    }

                    if($val['is_reason']>0) $type="无需处理"; else if($val['total_need_num']>0) $type="入库"; else if($val['total_need_num']< 0) $type="出库";  else $type="";

                    $list[$key]['type']= $type;
                    $list[$key]['status']= -100;
                    $list[$key]['status_two']= $val['status'];

                }else{

                    $list[$key]['d_status']= $this->getPackageStatus($val['status']);
                    //如果是退货，则显示退货状态
                    if(!empty(isset($val['return_status']))){
                        $val['status']=-1;
                    }
                }

            }
        }
        //如果是出库明细-直接count返回统计条数
        if($status==3){
            $resault['total']=count($list);
        }else{
            $resault['total']=$total;
        }

        $resault['list']=array_values($list);
        return $resault;
    }

    //生成入库大包
    public function  creatPackage()
    {
        $action        = $this->request->param('action/s', '');
        $ids_str         = $this->request->param('ids_str', '');
        //大包处理 ajax提交
        if($action == "ajaxCreatePackage"){
            $this->ajaxCreatePackage();
        }
        $packageList=db("sku_package")->where(['status'=>1])->select();
        $assign = [
            'action'=>'',
            'data'=>$packageList,
            'ids_str'=>$ids_str,
            'stock_m_type'=>'',
            'storehouseKV'=>'',
            'storeshelfKV'=>'',
            'factoryKV' => '',
            'isButton' =>1
        ];
        $template = $this->request->param('template', 'create_package');
        return $this->assign($assign)->fetch($template);
    }

    //无需处理
    public function  notNeedHandle()
    {
        $action        = $this->request->param('action/s', '');
        $ids_str         = $this->request->param('ids_str', '');

        //大包处理 ajax提交
        if($action == "notNeedHandleAction"){
            $list=$this->request->param();
            $is_reason=isset($list['data']['reason'])? $list['data']['reason']:0;
            $reason_content=isset($list['data']['reason_content'])? $list['data']['reason_content']:'';
            $strlist= explode(',',$list['data']['ids_str']);

            $strlistdata=[];
            //整理数据
            foreach($strlist as $key=>$val){
                if(!empty($val)){
                    $str=explode('|',$val);
                    $strlistdata['client_ordernum']=$str['0']?$str['0']:0;
                    $strlistdata['size_name']=$str['1'];
                    $strlistdata['is_reason']=$is_reason;
                    $strlistdata['reason_content']=$reason_content;
                    $strlistdata['tail_goods_dff']=$str['2'];
                    $strlistdata['need_put_num']=$str['2'];
                    $strlistdata['status']=4;
                    $strlistdata['create_time']=time();
                    //获取sku,工厂id
                    $dz=db('order')->where('client_ordernum',$str['0'])->field('id,sku,factory_id,tail_over_time')->find();
                    $strlistdata['sku']=$dz['sku'];
                    $strlistdata['order_id']=$dz['id'];
                    $strlistdata['factory_id']=$dz['factory_id'];
                    $strlistdata['tail_over_time']=$dz['tail_over_time'];
                    $strlistdata['is_get_into']=1;
                    db('sku_package_detail')->insert($strlistdata);
                    db('order_size')->where(['client_ordernum'=>$strlistdata['client_ordernum'],'size_name'=>$strlistdata['size_name']])->update(['is_tail_manage'=>1]);

                    $this->addOrderLog($dz['id'], $strlistdata['client_ordernum'], '尾货管理：无需处理操作，原因：'.$reason_content);
                };
            }

            return $this->success('操作成功', '');
        }
        $packageList=db("sku_package")->select();

        $assign = [
            'action'=>'',
            'data'=>$packageList,
            'ids_str'=>$ids_str,
            'stock_m_type'=>'',
            'storehouseKV'=>'',
            'storeshelfKV'=>'',
            'factoryKV' => '',
            'isButton' =>1
        ];
        $template = $this->request->param('template', 'not_need_handle');
        return $this->assign($assign)->fetch($template);
    }
    //新增入库单
    public function  addInvoice(){
        $action        = $this->request->param('action/s', '');
        //ajax提交
        if($action == "addInvoice"){
            $client_ordernum= $this->request->param('client_ordernum/s', '');
            $size_name= $this->request->param('size_name/s', '');
            $size_name=strtoupper($size_name);

            $orderInfo= db('order_size')->where(["client_ordernum"=>$client_ordernum,"size_name"=>$size_name])->find();

            if(!$orderInfo){
                return $this->error('订单号或尺码有误，找不到该信息!');
            }
            //是否在-尾货待处理中
            $isCountNum= (new SkuPackageV2())->doesItExitDeliveryOrder($client_ordernum,$size_name);
            if($orderInfo['is_tail_manage']==1 ||  $isCountNum>=1){
                return $this->error('该订单已在入库单中!');
            }

            $resault= db('order_size')->where(["client_ordernum"=>$client_ordernum,"size_name"=>$size_name])->update(['is_tail_manage'=>-1]);
            if($resault){
                return $this->success('操作成功', '');
            }else{
                return $this->error('数据异常' );
            }
        }
        $assign = [
            'action'=>'',
            'data'=>'',
            'ids_str'=>'',
            'stock_m_type'=>'',
            'storehouseKV'=>'',
            'storeshelfKV'=>'',
            'factoryKV' => '',
            'isButton' =>1
        ];
        $template = $this->request->param('template', 'add_invoice');
        return $this->assign($assign)->fetch($template);
    }
    //创建包
    private function ajaxCreatePackage(){

        $list=$this->request->param();

        if(!empty($list['data']['is_new_package']) && !empty($list['data']['package_num'])) return $this->error('不能同时选择 生成新包和加入其它包');
        if(empty($list['data']['is_new_package']) && empty($list['data']['package_num'])) return $this->error('请选择生成包的方式');
        $strlist= explode(',',$list['data']['ids_str']);
        $strlistdata=[];

        //整理数据
        foreach($strlist as $key=>$val){
            if(!empty($val)){
                $str=explode('|',$val);

                $strlistdata[$key]['client_ordernum']=$str['0']?$str['0']:0;
                $strlistdata[$key]['size_name']=$str['1'];
                $strlistdata[$key]['tail_goods_dff']=$str['2'];
                if($str['2'] <=0){
                    $this->error('尾货差异不能小于零');
                }
                $strlistdata[$key]['need_put_num']=$str['2'];
                $strlistdata[$key]['status']=1;
                $strlistdata[$key]['create_time']=time();
                //获取sku,工厂id
                $dz=db('order')->where('client_ordernum',$str['0'])->field('id as order_id,sku,factory_id')->find();

                $strlistdata[$key]['sku']=$dz['sku'];
                $strlistdata[$key]['order_id']=$dz['order_id'];
                $strlistdata[$key]['factory_id']=$dz['factory_id'];
            };
        }

        //入库主包表
        if($list['data']['is_new_package']==1 && $list['data']['package_num']==''){
            $max_package_mum=db('sku_package')->max('package_num')+1;//新包num
            if($max_package_mum<10001){$max_package_mum=10001;};
            $package_num_list=[$max_package_mum];
            $msg = "已生成新包";
            $packageList['status']=1;
            $packageList['create_time']=time();
            $packageList['package_num']=$max_package_mum;
            //新增加
            db('sku_package')->insert($packageList);

        }elseif($list['data']['is_new_package']==0){
            $package_str  =explode(',',$list['data']['package_num']); //传过来的，支持一个订单加入多个包，
            $package_num_list=$package_str;
            $msg = "已加入包：".$list['data']['package_num'];
        }

        //入库详细包表
        foreach($strlistdata as $value){
            foreach($package_num_list as $value2){
                $value['package_num']=$value2;
                db('sku_package_detail')->insert($value);
                db('sku_package_log')->insert($value);
            }
            //更新尺码表 状态
            db('order_size')->where(['client_ordernum'=>$value['client_ordernum'],'size_name'=>$value['size_name']])->update(['is_tail_manage'=>1]);
        }

        return $this->success($msg, '');
    }

    //修改尾货差异
    private function _changeSkuDiff(){
        return $this->success('保存成功', '');
    }

    /**
     * 尾货待处理-确定出库
     * @author hhx
     * @date 2022年8月12日
     */
    public function _checkout(){

        $list=$this->request->param();

        if(empty($list['ids_str'])) return $this->error('请选择要操作的数据');
        $strlist= explode(',',$list['ids_str']);
        $strlistdata=[];
         $SkuPackage=new SkuPackageV2();
            db()->startTrans();
            foreach($strlist as $key=>$val){
                if(!empty($val)){
                    $str=explode('|',$val);
                    $strlistdata['client_ordernum']=$str['0']?$str['0']:0;
                    $strlistdata['size_name']=$str['1'];
                    if($str['2']>=0){
                        $this->error(' 尾货差异不能大于等于0！ ');
                    }
                    //获取sku,工厂id
                    $dz=db('order')->where('client_ordernum',$str['0'])->field('id,sku,factory_id,tail_over_time')->find();

                    $stock_total_num=$SkuPackage->getSkuStockTotal($dz['sku'],$str['1']); //总库存
                    $occupy_num=$SkuPackage->getSkuStockOccupy($dz['id'],$dz['sku'],$str['1']); //占用库存

                    if(abs($str['2']) > ($stock_total_num-$occupy_num)){
                        $this->error(' 库存不足，不能出库！ 尾货差异数量不能大于总库存。当前已被占用库存: '.$occupy_num. '件');
                    }

                    $strlistdata['tail_goods_dff']=$str['2'];
                    $strlistdata['status']=3;
                    $strlistdata['create_time']=time();

                    $strlistdata['sku']=$dz['sku'];
                    $strlistdata['factory_id']=$dz['factory_id'];
                    $strlistdata['order_id']=$dz['id'];
                    $strlistdata['tail_over_time']=$dz['tail_over_time'];
                    $strlistdata['need_put_num']=$str['2'];

                    db('sku_package_detail')->insert($strlistdata);
                    db('sku_package_log')->insert($strlistdata);
                    //更新尺码表 状态
                    db('order_size')->where(['client_ordernum'=>$strlistdata['client_ordernum'],'size_name'=>$strlistdata['size_name']])->update(['is_tail_manage'=>1]);
                    $this->addOrderLog($dz['id'], $str['0'], "尾货管理-确定出库出库");

                };
            }
            db()->commit();
            return $this->Json(1,'出库成功');

    }

    /**
     * 打包待发货-确定发货
     * @author hhx
     * @date 2022年8月12日
     */
    public function _delivery(){
        $list=$this->request->param();
        if(empty($list['ids_str'])) return $this->error('请选择要操作的数据');
        $strlist= explode(',',$list['ids_str']);
        $strlistdata=[];
        try {
            db()->startTrans();
            foreach($strlist as $key=>$val){
                if(!empty($val)){
                    db('sku_package')->where(['package_num'=>$val])->update(['status'=>2,'update_time'=>time()]);
                    db('sku_package_detail')->where(['package_num'=>$val])->update(['status'=>2]);
                   // db('sku_package_log')->where(['package_num'=>$val])->update(['status'=>2]);
                  //  $this->addOrderLog($dz['id'], $str['0'], "出库");
                };
            }
            db()->commit();
            return $this->Json(1,'发货成功');
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 导出
     *
     */
    public function DataExpXls($fileName, &$data,$status) {
        if($status==0){
            $head = ['订单号','SKU','尺码','工厂','下单数','裁床数','车间数','出货数','尾货差异','状态','出入库方式','尾部完成时间'];
        }else{
            $head = ['大包编号','总件数','总单数','工厂','日期','状态'];
        }
        $params = [];
        $exportdata = [];

        foreach ($data as $k => $v) {
            switch ($status){
                case 0:
                    $exportdata[] = [
                        $v['client_ordernum'],
                        $v['sku'],
                        $v['size_name'],
                        isset($v['factory_name'])?$v['factory_name']:$v['factory_name_two'],
                        $v['order_count'],
                        $v['shicai_count'],
                        $v['jiaohuo_count'],
                        $v['daohuo_count'],
                        $v['tail_goods_dff'],
                        $v['pack_status_stay'],
                        $v['stock_outtype'],
                        $v['tail_over_time']==0 ? '':date('Y-m-d H:i:s', $v['tail_over_time'])
                    ];
                    break;
                default:
                    $exportdata[] = [
                        isset($v['package_num'])?$v['package_num']:$v['client_ordernum'],
                        $v['total_num'],
                        $v['total_ordernum'],
                        isset($v['factory_name'])?$v['factory_name']:$v['factory_name_two'],
                        $v['create_time']==0 ? '':date('Y-m-d H:i:S', $v['create_time']),
                        $v['d_status']

                    ];
            }

        }
        $params['file'] = $fileName;
        $params['sheet'] = [
            [
                'head' => $head, // 表头
                'data' => $exportdata,
            ],
        ];
        unset($data);
        plugins_run('excel/excel/export', $params);
    }
}

